package be.kul.osgi.ds.myagent.message;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;

import be.kul.osgi.ds.messageservice.MessageObject;
import be.kul.osgi.ds.myagent.MyAgent;

public class AskCapability implements BasicBehaviour{

	public String loc;
	public String capa;
	public String id;
	public MyAgent agent;
	
	public AskCapability(String id, String capa, MyAgent agent){
		this.capa = capa;
		this.agent = agent;
		this.id = id;
	}
	
	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return this.id;
	}

	@Override
	public void HandleMessage(MessageObject mo) {
		// TODO Auto-generated method stub
		if(mo.getPerformative()==MessageObject.GIVEBUNDLE){
			loc = mo.getContent();
			if(!agent.BundleLookup(capa)){
			
				try {
					InputStream input = new URL(loc).openStream();
					//this.agent.context.installBundle(null, input);
					Bundle b = this.agent.context.installBundle(loc);
					try{
						b.start();
					} catch (Exception e){
						
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BundleException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}
		}
	}

	public void AskforBundle(){
		MessageObject mo = new MessageObject(MessageObject.ASKBUNDLE);
		mo.setContent(capa);
		mo.setReceiver("multi");
		mo.setSender(this.agent.name);
		mo.setConversationId(this.id);
		//this.agent.getMessageService().send(mo);
		
		String message = agent.getMessageService().serialize(mo);
		
		System.out.println(message);
		
		agent.getComm().sendmulticast(message);
	}
	
	@Override
	public boolean isInterested(MessageObject mo) {
		// TODO Auto-generated method stub
		if(mo.getConversationId().equals(this.id) && mo.getPerformative()==MessageObject.GIVEBUNDLE){
			return true;
		}
		return false;
	}


	@Override
	public void start() {
		// TODO Auto-generated method stub
		AskforBundle();
	}

}
